﻿using System;
using System.Reflection;
using Microsoft.SharePoint;
using Kiiro.Common.Entities;
using Kiiro.Common.Utility;
using Kiiro.ExceptionManagement;

using UserFieldNames = Kiiro.Common.Utility.Constants.UserFieldNames;

namespace Kiiro.Model.EventHandlers.ItemEventHandlers
{
    public class UserItemEventReceiver : SPItemEventReceiver
    {
        /// <summary>
        /// Asynchronous After event that occurs after a new item has been added to its containing object.
        /// </summary>
        /// <param name="properties">
        /// A Microsoft.SharePoint.SPItemEventProperties object that represents properties of the event handler.
        /// </param>
        public override void ItemAdded ( SPItemEventProperties properties )
        {
            try
            {
                LicensingModel.InvalidateActiveUsersCount ( properties.SiteId, properties.RelativeWebUrl );
            }
            catch ( Exception ex )
            {
                ExceptionManager.HandleException ( new Exception ( String.Format ( "Exception in: {0}\r\n {1}", MethodInfo.GetCurrentMethod ( ).Name, ex.ToString ( ) ) ), true );
            }

            base.ItemAdded ( properties );
        }

        /// <summary>
        /// Synchronous Before event that occurs when an existing item is changed, for example, when the user changes data in one or more fields.
        /// </summary>
        /// <param name="properties">
        /// A Microsoft.SharePoint.SPItemEventProperties object that represents properties of the event handler.
        /// </param>
        public override void ItemUpdating ( SPItemEventProperties properties )
        {
            try
            {
                if ( properties.ListItem != null )
                {
                    User user = SPDataHelpers.MakeUser ( properties.ListItem, properties.SiteId, properties.RelativeWebUrl );

                    if ( user != null && user.Login != null && !user.IsSharePointAccount )
                    {
                        if ( properties.AfterProperties [ UserFieldNames.StatusNote ] != null )
                        {
                            string newStatus = SPDataHelpers.GetStringValue ( properties.AfterProperties, UserFieldNames.StatusNote );

                            if ( newStatus != null && newStatus != user.StatusNote )
                            {
                                ActivityHistory activity = PopulateUserHistory ( user, newStatus, DateTime.Now );
                                activity.EventType = EventType.Updated;

                                ActivityHistoryModel.Save ( activity, properties.SiteId, properties.RelativeWebUrl );
                            }
                        }
                    }
                }
            }
            catch ( Exception ex )
            {
                ExceptionManager.HandleException ( new Exception ( String.Format ( "Exception in: {0}\r\n {1}", MethodInfo.GetCurrentMethod ( ).Name, ex.ToString ( ) ) ), true );
            }

            if ( !properties.Cancel )
                base.ItemUpdating ( properties );
        }

        /// <summary>
        /// Synchronous Before event that occurs before an existing item is completely deleted.
        /// </summary>
        /// <param name="properties">
        /// A Microsoft.SharePoint.SPItemEventProperties object that represents properties of the event handler.
        /// </param>
        public override void ItemDeleting ( SPItemEventProperties properties )
        {
            try
            {
                LicensingModel.InvalidateActiveUsersCount ( properties.SiteId, properties.RelativeWebUrl );
            }
            catch ( Exception ex )
            {
                ExceptionManager.HandleException ( new Exception ( String.Format ( "Exception in: {0}\r\n {1}", MethodInfo.GetCurrentMethod ( ).Name, ex.ToString ( ) ) ), true );
            }

            base.ItemDeleting ( properties );
        }

        /// <summary>
        /// 
        /// </summary>
        private ActivityHistory PopulateUserHistory ( User user, string statusNote, DateTime date )
        {
            ActivityHistory activity = new ActivityHistory ( user );

            // overwrite values
            activity.CreatedBy = user;
            activity.CreatedDate = date;
            activity.ModifiedBy = user;
            activity.ModifiedDate = date;
            activity.Description = statusNote;

            activity.ActivityItemType = ItemType.User;
            activity.EditType = EditType.Created;

            return activity;
        }

        #region Unused

        /// <summary>
        /// Synchronous Before event that occurs when a new item is added to its containing object.
        /// </summary>
        /// <param name="properties">
        /// A Microsoft.SharePoint.SPItemEventProperties object that represents properties of the event handler.
        /// </param>
        public override void ItemAdding ( SPItemEventProperties properties )
        {
            base.ItemAdding ( properties );
        }

        /// <summary>
        /// Asynchronous After event that occurs after an existing item is changed, for example, when the user changes data in one or more fields.
        /// </summary>
        /// <param name="properties">
        /// A Microsoft.SharePoint.SPItemEventProperties object that represents properties of the event handler.
        /// </param>
        public override void ItemUpdated ( SPItemEventProperties properties )
        {
            base.ItemUpdated ( properties );
        }

        /// <summary>
        /// Asynchronous After event that occurs after an existing item is completely deleted.
        /// </summary>
        /// <param name="properties">
        /// A Microsoft.SharePoint.SPItemEventProperties object that represents properties of the event handler.
        /// </param>
        public override void ItemDeleted ( SPItemEventProperties properties )
        {
            base.ItemDeleted ( properties );
        }

        #endregion

    }
}

/*************************************************************************
 * 
 * $Log: /Internal Projects/Kiiro/Kiiro.Model/EventHandlers/ItemEventHandlers/UserItemEventReceiver.cs $
 * 
 * 14    2/08/10 5:04p Camerons
 * 
 * 13    1/25/10 1:17p Camerons
 * 
 * 12    1/12/10 12:03p Camerons
 * 
 * 11    26/11/09 10:35a Camerons
 * 
 * 10    17/11/09 6:46p Camerons
 * 
 * 9     10/11/09 11:40a Camerons
 * 
 * 8     7/10/09 5:14p Camerons
 * Case #281, #285: Update SPDataHelpers.MakeUser to take SiteCollectionId
 * and ServerRelativeUrl as params. Used to properly determine the group
 * memberships.
 * 
 * 7     21/09/09 3:30p Camerons
 * First batch of changes for 1.1.x.x - Security groups update
 * 
 * 6     4/09/09 3:18p Camerons
 * 
 * 1     4/09/09 10:06a Camerons
 * 
 * 4     17/08/09 10:29a Camerons
 * Added check-in comments section
 * 
 ************************************************************************/